package com.activit.test;

import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * @ClassName ActivitiDemo
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/25 11:28
 * @Version 1.0
 **/
public class ActivitiDemo {

    //测试部署
    @Test
    public void testDeeploment() {

        //1.获取配置类processEngineConfiguration
        ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResource("activiti.cfg.xml", "processEngineConfiguration");

        //2.获取配置类processEngine工作流引擎
        ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine();

        //3.获取配资源部署类的相关service -[ Repository ]
        RepositoryService repositoryService = processEngine.getRepositoryService();

        //4.创建流程部署
        DeploymentBuilder builder = repositoryService.createDeployment();
        builder.name("出差申请流程");
        builder.addClasspathResource("bpmn/evection.bpmn20.xml");
        builder.addClasspathResource("bpmn/evection.png");

        Deployment deployment = builder.deploy();


        System.out.println("流程部署id=" + deployment.getId());

        System.out.println("流程部署name=" + deployment.getName());

    }

    /**
     * 开启流程：
     * <p>
     * act_hi_actinst                   流程实例执行历史
     * act_hi_identitylink              流程的参与用户历史信息
     * act_hi_procinst                  流程实例历史信息
     * act_hi_taskinst                  流程任务历史信息
     * act_ru_execution                 流程执行信息
     * act_ru_identitylink              流程的参与用户信息
     * act_ru_task                      任务信息
     */
    @Test
    public void testRuntimeDemo() {

        //采用默认方式获取工作流引擎
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();

        RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        ProcessInstance evection = runtimeService.startProcessInstanceByKey("evection");

        System.out.println("流程定义ID=" + evection.getProcessDefinitionId());
        System.out.println("流程实例ID=" + evection.getId());
        System.out.println("当前活动ID=" + evection.getActivityId());

    }


    /**
     * 查询个人待执行的任务
     */
    @Test
    public void testFindPersonalTaskList() {
        //1.获取引擎
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        //2.获取taskService
        TaskService taskService = defaultProcessEngine.getTaskService();
        //3.根据key查询任务
        List<Task> list = taskService.
                createTaskQuery().//创建查询
                processDefinitionKey("evection").//流程实例的key
                taskAssignee("张三").//要查询的负责人
                list();

        for (Task task : list) {
            System.out.println("实例-id" + task.getProcessInstanceId());
            System.out.println("任务-id" + task.getId());
            System.out.println("任务当前负责人信息" + task.getAssignee());
            System.out.println("任务名字" + task.getName());
        }

    }

    /**
     * 查询个人待执行的任务
     */
    @Test
    public void compeletTask() {

        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();

        Task task = taskService.createTaskQuery().processDefinitionKey("evection").taskAssignee("张三").singleResult();

        taskService.complete(task.getId());


    }


    @Test
    public void taskBy李四() {
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();

        //获取李四对应的任务
        Task task = taskService.createTaskQuery().processDefinitionKey("evection").taskAssignee("李四").singleResult();
        System.out.println(task);
        taskService.complete(task.getId());

    }

    @Test
    public void taskBy王五() {
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();

        //获取王五 对应的任务
        Task task = taskService.createTaskQuery().processDefinitionKey("evection").taskAssignee("王五").singleResult();
        System.out.println(task);
        taskService.complete(task.getId());

    }

    @Test
    public void taskBy赵六() {
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();

        //获取赵六 对应的任务
        Task task = taskService.createTaskQuery().processDefinitionKey("evection").taskAssignee("赵六").singleResult();
        System.out.println(task);
        taskService.complete(task.getId());

    }


    /**
     * 使用Zip打包 部署资源
     * [之前单独添加的一个资源文件,现在将多个bpmn打包文件通过zip打包]
     */
    @Test
    public void deployProcessByZip(){

        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();

        InputStream inputStream =this.
                getClass().         //获取类的信息
                getClassLoader().   //获取整个工程的信息
                getResourceAsStream("bpmn/newAct.zip");


        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        Deployment deploy = repositoryService.createDeployment()
                .addZipInputStream(zipInputStream)
                .deploy();

        System.out.println("部署信息："+deploy);
        System.out.println("流程name:"+deploy.getName());

//        部署信息：DeploymentEntity[id=1, name=null]
//        流程name:null

    }


    @Test
    public void repositoryTest(){


        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        List<ProcessDefinition> list = definitionQuery
                .processDefinitionName("出差申请")
                .orderByProcessDefinitionVersion() //根据版本排序
                .asc() //排序
                .list();


        for (ProcessDefinition ts: list) {
            System.out.println("ID："+ts.getId());
            System.out.println("名字："+ts.getName());
            System.out.println("KEY："+ts.getKey());
            System.out.println("版本："+ts.getVersion());

        }

    }

    /**
     * 删除已经部署的流程
     */
    @Test
     public void deleteProcess(){
         ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
         RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();

         //通过部署id删除部署
         repositoryService.deleteDeployment("2501");
     }


    /**
     * 删除已经部署、流程已经有使用实例，并且未完成
     */
    @Test
    public void deleteRuntimeProcess(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();


        //使用True,开启级联删除
        repositoryService.deleteDeployment("2501",true);

    }


    /**
     * 下载资源文件
     */
    @Test
    public void downRepository() throws Exception {
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RepositoryService repositoryService = defaultProcessEngine.getRepositoryService();

        ProcessDefinition evection = repositoryService.createProcessDefinitionQuery().processDefinitionKey("evection").singleResult();


        String deploymentId = evection.getDeploymentId();
        String diagramImageName = evection.getDiagramResourceName();
        String resourceName = evection.getResourceName();

        InputStream inIoImage =repositoryService.getResourceAsStream(deploymentId, diagramImageName);
        InputStream inIoBPMN = repositoryService.getResourceAsStream(deploymentId, resourceName);


        FileOutputStream fileBpmn = new FileOutputStream(new File("D:\\IDEA-workspace\\private\\Learning_test\\Activti7\\evection.bpmn"));
        FileOutputStream filePng = new FileOutputStream(new File("D:\\IDEA-workspace\\private\\Learning_test\\Activti7\\evection.png"));

        IOUtils.copy(inIoImage, filePng);
        IOUtils.copy(inIoBPMN, fileBpmn);

        inIoBPMN.close();
        inIoImage.close();
        fileBpmn.close();
        filePng.close();

    }


    @Test
    public void getHistoryInfo(){
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = defaultProcessEngine.getHistoryService();

        HistoricActivityInstanceQuery historicQuery = historyService.createHistoricActivityInstanceQuery();

        HistoricActivityInstanceQuery historicActivityInstanceQuery = historicQuery.processInstanceId("10001");
        System.out.println(historicActivityInstanceQuery);
        System.out.println("====");

        List<HistoricActivityInstance> list = historicQuery.list();
        System.out.println(list);
        System.out.println("====");
    }







}
